package com.qall.onlie_code.process;

import com.qall.util.FileUtil;
import com.qall.util.InvokeUtil;
import com.qall.util.LOGUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class CodeProcess {

    @Value("${code.path}")
    private String javaFilePath;

    @Value("${class.file-prefix}")
    private String classFilePrefix;

    @Value("${class.file-path}")
    private String classFilePath;

    @Value("${class.name}")
    private String classPath ;

    @Value("${method.name}")
    private String methodName;

    @Value("${class.name}")
    private String className;


    //
    public String process(String code) {
        String ret = "";
        // 文件写入磁盘
        FileUtil.writeToFile(code, javaFilePath);
        List<String> options = new ArrayList<>();

        options.add("-d");
        options.add(classFilePrefix);
        try {
            CompileUtil.compileAndCopyFiles(javaFilePath, classFilePrefix, options, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  字节码加载进入内存
        MyClassLoader myClassLoader = new MyClassLoader(className);
        try {
            myClassLoader.loadClass(classFilePath);
        } catch (ClassNotFoundException e) {
            ret = LOGUtil.getStackTraceInfo(e);
        }
        // 执行字节码中的exec 函数
        try {
            Object instance = Class.forName(classPath, true, myClassLoader).newInstance();
            ret = InvokeUtil.invokeMethod(methodName, new String[]{}, new String[]{}, instance);
            return ret;
        } catch (InstantiationException e) {
            ret = LOGUtil.getStackTraceInfo(e);
        } catch (IllegalAccessException e) {
            ret = LOGUtil.getStackTraceInfo(e);
        } catch (ClassNotFoundException e) {
            ret = LOGUtil.getStackTraceInfo(e);
        }
        // 返回执行结果
        return ret;
    }

}
